/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
// Copyright tang.  All rights reserved.
// https://gitee.com/inrgihc/dbswitch
//
// Use of this source code is governed by a BSD-style license
//
// Author: tang (inrgihc@126.com)
// Date : 2020/1/2
// Location: beijing , china
/////////////////////////////////////////////////////////////
package com.je.meta.util.database;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * JDBC的URL相关工具类
 *
 * @author tang
 */
public class JdbcUrlUtils {

    private static Pattern patternWithParam = Pattern.compile(
            "(?<protocol>^.+):(?<dbtype>.+)://(?<addresss>.+):(?<port>.+)/(?<schema>.+)\\?(?<path>.+)");

    private static Pattern patternSimple = Pattern.compile(
            "(?<protocol>^.+):(?<dbtype>.+)://(?<addresss>.+):(?<port>.+)/(?<schema>.+)");

    /**
     * 从MySQL数据库的JDBC的URL中提取数据库连接相关参数
     *
     * @param jdbcUrl JDBC连接的URL字符串
     * @return Map 参数列表
     */
    public static Map<String, String> findParamsByMySqlJdbcUrl(String jdbcUrl) {
        Pattern pattern = null;
        if (jdbcUrl.indexOf('?') > 0) {
            pattern = patternWithParam;
        } else {
            pattern = patternSimple;
        }

        Matcher m = pattern.matcher(jdbcUrl);
        if (m.find()) {
            Map<String, String> ret = new HashMap<String, String>();
            ret.put("protocol", m.group("protocol"));
            ret.put("dbtype", m.group("dbtype"));
            ret.put("addresss", m.group("addresss"));
            ret.put("port", m.group("port"));
            ret.put("schema", m.group("schema"));

            if (m.groupCount() > 5) {
                ret.put("path", m.group("path"));
            }

            return ret;
        } else {
            return null;
        }
    }

}
